package org.pearl.order.service.impl;

import com.google.common.collect.Maps;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.pearl.order.dao.OrderTblMapper;
import org.pearl.order.entity.OrderTbl;
import org.pearl.order.service.OrderTccService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * Created by TD on 2022/1/26
 */
@Slf4j
@Service
public class OrderTccServiceImpl implements OrderTccService {


    @Autowired
    OrderTblMapper orderTblMapper;

    @Override
    public void createOrder(String userId, String code, Long count) {
        log.info("Assign Service Begin ... xid: " + RootContext.getXID() + "\n");
        // 创建订单
        OrderTbl orderTbl = new OrderTbl();
        orderTbl.setUserId(userId);
        orderTbl.setCommodityCode(code);
        orderTbl.setCount(count.intValue());
        orderTblMapper.insert(orderTbl);
    }


    @Override
    public boolean commit(BusinessActionContext actionContext) {
        String xid = actionContext.getXid();
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        String xid = actionContext.getXid();
        Object userId = actionContext.getActionContext("userId");
        HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
        objectObjectHashMap.put("user_id", userId.toString());
        orderTblMapper.deleteByMap(objectObjectHashMap);
        log.info(" rollback, xid:" + xid);
        return true;
    }
}
